package com.atguigu.study.base.cas;

import javax.swing.text.TabSet;
import java.util.TreeSet;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * @Author 快点干早点散
 * @Create 2025/4/24 19:47
 * Description:100个线程，每个线程加100次，求最后的number值
 */
public class CASDemo {
    private int number;

    public int getNumber() {
        return number;
    }

    public synchronized void setNumber() {
        ++number;
    }

    public static void main(String[] args) {
     /*   CountDownLatch countDownLatch = new CountDownLatch(100);
        CASDemo casDemo = new CASDemo();
        for (int i =1; i <=100; i++) {
            new Thread(() -> {
                for (int j = 1; j<=100; j++) {
                    casDemo.setNumber();

                }
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }
//        try {
//            TimeUnit.SECONDS.sleep(1);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("casDemo = " + casDemo.getNumber());
    }*/
        CASDemo casDemo = new CASDemo();
        CyclicBarrier cyclicBarrier = new CyclicBarrier(100,()->{System.out.println("casDemo="+casDemo.getNumber());});
        for (int i = 1; i <=100; i++) {
            new Thread(() -> {


                    casDemo.setNumber();
                    try {
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    } catch (BrokenBarrierException e) {
                        throw new RuntimeException(e);
                    }


            }, "").start();
        }
//        System.out.println("casDemo = " + casDemo.getNumber());
    }
}
